﻿// ===============================================================================
// Project Name        :    Gfw.Repositories.Account
// Project Description :    
// ===============================================================================
// Class Name          :    ActCompanyBargainRepository
// Namespace:          :    Gfw.Repositories.Account
// Class Version       :    v1.0.0.0
// Class Description   :    
// CLR Version:        :    4.0.30319.17626
//Author               :    lif
// Machine             :    ADICO-PC
// Create Time         :    2012/6/24 10:18:39
// Update Time         :    2012/6/24 10:18:39
// ===============================================================================
// Copyright © lif 2012 . All rights reserved.
// ===============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gfw.Repository;
using Gfw.Models.Account;
using System.Diagnostics;

namespace Gfw.Repositories.Account
{
    public class ActCompanyBargainRepository : Repository<ActCompanyBargain>
    {
        #region 增加记录

        public virtual void AddIncome(string userId, int type, decimal amount, string message,
            string awardSerialNo = null, string taxationSerialNo = null, UnitOfWork unitOfWork = null)
        {
            ActCompanyBargain bargain = new ActCompanyBargain()
            {
                Id = Guid.NewGuid().ToString(),
                Userid = userId,
                TradeType = type,
                Income = amount,
                Outlay = 0,
                TradeDate = DateTime.Now,
                TradeAbstract = message,
                AwardSerialNo = awardSerialNo,
                TaxationSerialNo = taxationSerialNo
            };
            Save(bargain, unitOfWork);
        }

        public virtual void AddOutlay(string userId, int type, decimal amount, string message, string awardSerialNo, UnitOfWork unitOfWork = null)
        {
            ActCompanyBargain bargain = new ActCompanyBargain()
            {
                Id = Guid.NewGuid().ToString(),
                Userid = userId,
                TradeType = type,
                Income = 0,
                Outlay = amount,
                TradeDate = DateTime.Now,
                TradeAbstract = message,
                AwardSerialNo = awardSerialNo

            };
            Save(bargain, unitOfWork);
        }

        #endregion

        public decimal GetProfit(DateTime start, DateTime end)
        {
            string sqlFormat =
                "select sum(income)-sum(outlay) as Profit FROM act_company_bargain where TradeDate>:start and TradeDate<=:end and TradeType>100";
            var query = Session.CreateSQLQuery(sqlFormat).SetDateTime("start", start).SetDateTime("end", end)
                .UniqueResult<decimal>();
            return query;
        }

        public decimal GetBonus(DateTime start, DateTime end)
        {
            string sqlFormat =
                "select sum(income)-sum(outlay) as Profit FROM act_company_bargain where TradeDate>:start and TradeDate<=:end and TradeType<100";
            var query = Session.CreateSQLQuery(sqlFormat).SetDateTime("start", start).SetDateTime("end", end)
                .UniqueResult<decimal>();
            return query;
        }


        #region 统计利润

        /// <summary>
        /// 统计公司利润
        /// </summary>
        /// <param name="statisticsStartDate"></param>
        /// <param name="statisticsEndDate"></param>
        /// <param name="sumAnnualFee"></param>
        /// <param name="sumSellStock"></param>
        /// <param name="sumToCashTax"></param>
        /// <param name="sumTax"></param>
        /// <param name="sumChangeInformation"></param>
        /// <param name="sumBonus"></param>
        /// <param name="sumOthers"></param>
        /// <returns>成功 | 失败</returns>
        public bool StatisticsCompanyProfit(DateTime statisticsStartDate, DateTime statisticsEndDate,
            out decimal sumAnnualFee, out decimal sumSellStock, out decimal sumToCashTax, out decimal sumTax, out decimal sumChangeInformation, 
            out decimal sumBonus, out decimal sumOthers)
        {
            sumAnnualFee = sumSellStock = sumToCashTax = sumTax = sumChangeInformation = sumBonus = sumOthers = 0.0M;

            try
            {
                // Gfw.Infrastructure.Account.CompanyTradeTypeEnum
                // 1: AnnualFee 年费
                // 2: ToCashTax 提现的手续费 10%
                // 3: Tax 动态奖金税收 2%
                // 4: Sell_Stock 股票销售收益 8%
                // 6: Pay_Bonus 分红支出
                // 7: Pay_Others 其它费用
                // 8: ChangeInformation 修改会员绑定资料、重置密码费用（每次100）
                var result = Session.CreateQuery("select TradeType as TradeType, sum(Income) as SumIncome, sum(Outlay) as SumOutlay from ActCompanyBargain " +
                    " where TradeDate>=:start and TradeDate<=:end " +
                    " group by TradeType having TradeType in (1,2,3,4,6,7,8) order by TradeType")
                    .SetDateTime("start", statisticsStartDate).SetDateTime("end",statisticsEndDate)
                    .List<object[]>();

                if (result != null)
                {
                    for (int i = 0; i < result.Count; i++)
                    {
                        if (result[i] != null)
                        {
                            int tradeEnum = int.Parse(result[i][0] != null ? result[i][0].ToString() : "-1");
                            switch (tradeEnum)
                            {
                                // 增值操作
                                case 1: // AnnualFee
                                    sumAnnualFee = decimal.Parse(result[i][1] != null ? result[i][1].ToString() : "0.0");
                                    break;

                                case 2: // ToCashTax
                                    sumToCashTax = decimal.Parse(result[i][1] != null ? result[i][1].ToString() : "0.0");
                                    break;

                                case 3: // Tax
                                    sumTax = decimal.Parse(result[i][1] != null ? result[i][1].ToString() : "0.0");
                                    break;

                                case 4: // SellStock
                                    sumSellStock = decimal.Parse(result[i][1] != null ? result[i][1].ToString() : "0.0");
                                    break;

                                case 8: // ChangeInformation
                                    sumChangeInformation = decimal.Parse(result[i][1] != null ? result[i][1].ToString() : "0.0");
                                    break;


                                // 扣费操作
                                case 6: // Pay_Bonus
                                    sumBonus = decimal.Parse(result[i][2] != null ? result[i][2].ToString() : "0.0");
                                    break;

                                case 7: // Pay_Others
                                    sumOthers = decimal.Parse(result[i][2] != null ? result[i][2].ToString() : "0.0");
                                    break;

                                default:
#if DEBUG
                                    Debug.WriteLine("Trade Enum: " + tradeEnum);
#endif
                                    break;
                            } // switch
                        } // if
                    } // for
                } // if

                return true;
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                return false;
            }
        }

        #endregion

    }
}
